package itpenguin.train;

import itpenguin.train.common.Train;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public abstract class TrainPositions extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	private static final SimpleDateFormat DT_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
        
		resp.setHeader("Access-Control-Allow-Origin", "http://travel.it-penguin.com");
		PrintWriter writer = resp.getWriter();
		
        List<? extends Train> trains = getTrainList();
        Map<String, Object> map = new HashMap<String, Object>();
        synchronized (DT_FORMAT) {
        	DT_FORMAT.setTimeZone(getTimeZone());
            map.put("localTime", DT_FORMAT.format(new Date()));
		}
        map.put("trains", trains);
        writer.print(JSONObject.fromObject(map).toString());
        writer.flush();

    }
	
	protected abstract List<? extends Train> getTrainList() throws IOException;
	
	protected abstract TimeZone getTimeZone();

}